from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response

from goods.models import SKU
from utils.pagination import StandardResultsSetPagination

"""
所谓的静态化 其实就是 让用户 直接去访问 我们处理好的 html页面

问题:
    我们首页的数据 会发生变化


1. 先查询数据库的数据
2. 通过模板来渲染数据
3. 模板渲染好的html 写入到指定 的文件目录

"""

"""
用户选择不同的热销分类,我们返回相应的热销产品

1.接收分类id
2.根据分类id获取商品信息 [SKU,SKU]
3.进行序列化操作(将对象转换为字典或者json)
4.返回响应
GET   /goods/categories/(?P<category_id>\d+)/hotskus/

"""
#热销商品获取第一种方式
# APIView
# GenericAPIView
# ListAPIView,RetriveAPIView
from rest_framework.views import APIView
from .serializers import HotSKUSerializer
# class HotSKUView(APIView):
#
#     def get(self,request,category_id):
#         # 1.接收分类id
#         # 2.根据分类id获取商品信息 [SKU,SKU]
#         #分类
#         # category 相当于一个实例对象 category = 对象
#         #如果想给category赋值一个id
#         #这个时候只能使用数据表中的 字段名 = 值
#         # category_id = 1
#         #category = GoodCategory.objects.get(category_id=category_id)
#         #上架
#         skus = SKU.objects.filter(is_launched = True,category_id=category_id).order_by('-sales')[:2]
#
#         # 3.进行序列化操作(将对象转换为字典或者json)
#         serializer = HotSKUSerializer(skus,many=True)
#         # 4.返回响应
#         return Response(serializer.data)

#热销商品获取第二种方式 三级视图
from rest_framework.generics import ListAPIView
class HotSKUView(ListAPIView):

    pagination_class = None

    serializer_class = HotSKUSerializer

    def get_queryset(self):

        category_id = self.kwargs['category_id']

        return SKU.objects.filter(is_launched = True,category_id=category_id).order_by('-sales')[:2]

from rest_framework.filters import OrderingFilter
from rest_framework.pagination import PageNumberPagination
class SKUAPIView(ListAPIView):
    """
    1.根据分类获取所有数据
    2.排序
    3.分页

    GET  /goods/categories/(?P<category_id>\d+)/skus/?ordering=-price&page=2&page_size=2

    """
    #排序实现
    filter_backends = [OrderingFilter]
    ordering_fields = ['price','sales','create_time']

    #分页
    # pagination_class = StandardResultsSetPagination

    serializer_class = HotSKUSerializer

    def get_queryset(self):

        category_id = self.kwargs['category_id']

        return SKU.objects.filter(is_launched = True,category_id=category_id)

"""
搜索的步骤分为2步:
    1.elasticsearch 帮助我们实现搜索引擎的功能
      我们通过docker的方式让它运行起来
    2.haystack 去连接 elasticsearch
      ① 配置 haystack
      ② 定义搜索索引类,让elasticsearch去分词来创建全文索引
      ③ 搜索
"""

from .serializers import SKUIndexSerializer
from drf_haystack.viewsets import HaystackViewSet

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer
